package cn.jeeweb.web.modules.sys.controller;

import cn.jeeweb.common.utils.FastJsonUtils;
import cn.jeeweb.web.aspectj.annotation.Log;
import cn.jeeweb.web.modules.sys.entity.Dict;
import cn.jeeweb.web.modules.sys.entity.DictGroup;
import cn.jeeweb.web.modules.sys.entity.Menu;
import cn.jeeweb.web.modules.sys.service.IDictGroupService;
import cn.jeeweb.common.http.Response;
import cn.jeeweb.common.mvc.annotation.ViewPrefix;
import cn.jeeweb.common.mvc.controller.BaseBeanController;
import cn.jeeweb.common.mybatis.mvc.wrapper.EntityWrapper;
import cn.jeeweb.common.security.shiro.authz.annotation.RequiresMethodPermissions;
import cn.jeeweb.common.security.shiro.authz.annotation.RequiresPathPermission;
import cn.jeeweb.common.utils.StringUtils;
import cn.jeeweb.web.modules.sys.service.IDictService;
import cn.jeeweb.web.modules.sys.service.IMenuService;
import cn.jeeweb.web.utils.PageRequest;
import cn.xjzn.framework_Core.ModuleActionType;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/sys/dict/group")
@ViewPrefix("modules/sys/dict/group")
@RequiresPathPermission("sys:dict")
@Log(title = "字典分组")
public class DictGroupController extends BaseBeanController<DictGroup> {

	@Autowired
	private IDictGroupService dictGroupService;

	@Autowired
	private IMenuService menuService;

	@Autowired
	private IDictService dictService;

	/**
	 * 根据页码和每页记录数，以及查询条件动态加载数据
	 *
	 * @param request
	 * @throws IOException
	 */
	@GetMapping(value = "list")
	@Log(logType = ModuleActionType.SELECT)
	@RequiresMethodPermissions("group:list")
	public void list( HttpServletRequest request) throws IOException {
		//加入条件
		EntityWrapper<DictGroup> entityWrapper = new EntityWrapper<>(DictGroup.class);
		entityWrapper.orderBy("createDate",false);
		String keyword=request.getParameter("keyword");
		String moduleId = request.getParameter("moduleId");
		if (!StringUtils.isEmpty(keyword)){
			entityWrapper.like("name",keyword);
		}
		if (!StringUtils.isEmpty(moduleId)){
			entityWrapper.eq(true,"moduleId",moduleId);
		}
		// 预处理
		Page pageBean = dictGroupService.selectPage(PageRequest.getPage(),entityWrapper);
		Menu search = new Menu();
		search.setType("1");
		List<Menu> menus = menuService.findMenuList(search);
		List<DictGroup> dictGroups = pageBean.getRecords();
		if(dictGroups != null && dictGroups.size() > 0){
			for(DictGroup dictGroup : dictGroups){
				dictGroup.setModuleName("");
				if(menus == null || menus.size() == 0){
					break;
				}else{
					for(Menu menu : menus){
						if(menu.getId().equals(dictGroup.getModuleId())){
							dictGroup.setModuleName(menu.getName());
							break;
						}
					}
				}
			}
		}
		FastJsonUtils.print(pageBean,DictGroup.class,"id,name,code,remarks,isSys,moduleId,moduleName");
//		return Response.ok(null,pageBean,DictGroup.class,"id,name,code,remarks,usable");
	}

	@PostMapping("add")
	@Log(logType = ModuleActionType.INSERT)
	@RequiresMethodPermissions("group:add")
	public Response add(DictGroup entity, BindingResult result,
						   HttpServletRequest request, HttpServletResponse response) {
		// 验证错误
		this.checkError(entity,result);
		DictGroup dictGroup = new DictGroup();
		dictGroup.setCode(entity.getCode());
		DictGroup old = dictGroupService.getDictGroupByCode(dictGroup);
		if(old != null){
			return Response.error("保存失败，字典分组Code值已存在");
		}else{
			try {
				dictGroupService.insert(entity);
			}catch (Exception e){
				return Response.error("保存失败，请联系管理员");
			}
			return Response.ok("添加成功");
		}

	}

	@PostMapping("{id}/update")
	@Log(logType = ModuleActionType.UPDATE)
	@RequiresMethodPermissions("group:update")
	public Response update(DictGroup entity, BindingResult result,
						   HttpServletRequest request, HttpServletResponse response) {
		// 验证错误
		this.checkError(entity,result);
		DictGroup dictGroup = new DictGroup();
		dictGroup.setCode(entity.getCode());
		DictGroup old = dictGroupService.getDictGroupByCode(dictGroup);
		if(old != null && !old.getId().equals(entity.getId())){
			return Response.error("保存失败，字典分组Code值已存在");
		}else{
			try {
				dictGroupService.insertOrUpdate(entity);
			}catch (Exception e){
				return Response.error("保存失败，请联系管理员");
			}
			return Response.ok("更新成功");
		}
	}

	@PostMapping("{id}/delete")
	@RequiresMethodPermissions("group:delete")
	public Response delete(@PathVariable("id") String id) {

		EntityWrapper<Dict> entityWrapper = new EntityWrapper<Dict>(Dict.class);
		entityWrapper.eq("gid",id);
		List<Dict> list = dictService.selectList(entityWrapper);
		if(list != null && list.size() > 0){
			return Response.error("删除失败，请先删除字典分组下的字典值");
		}else{
			dictGroupService.deleteById(id);
			return Response.ok("删除成功");
		}

	}

	@RequestMapping(value = "/forceRefresh", method = RequestMethod.POST)
	@ResponseBody
	@Log(logType = ModuleActionType.OTHER,title = "字典刷新")
	@RequiresMethodPermissions("force:refresh")
	public Response forceRefresh(HttpServletRequest request, HttpServletResponse response) {
		try {
			// DictUtils.clear();
		} catch (Exception e) {
			e.printStackTrace();
			return Response.error("字典刷新失败" + e.getMessage());
		}
		return Response.ok("字典刷新成功");
	}

}